package com.smartleanx.module.hrm.service.examine.util;

import com.smartleanx.module.hrm.service.examine.util.exception.ResultException;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * @author guo
 */
public class DateUtil {

    /**
     * 当前时间加*分钟数
     *
     * @param minuteNum 分钟数
     * @return
     */
    public static Date reduceMinute(Integer minuteNum) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.MINUTE, -minuteNum);
        Date newTime = calendar.getTime();
        return newTime;
    }

    /**
     * 时间加十五分钟
     */
    public static String dateFormat() {
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();

        // 增加15分钟
        LocalDateTime plus15Minutes = now.plusMinutes(15);

        // 创建一个DateTimeFormatter对象来定义日期时间的格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 将增加15分钟后的时间转换为字符串
        String formattedDateTime = plus15Minutes.format(formatter);

        // 输出结果
        System.out.println("当前时间: " + now.format(formatter));
        System.out.println("增加15分钟后的时间（字符串）: " + formattedDateTime);
        return formattedDateTime;
    }


    /**
     * 时间加十五分钟
     */
    public static String dateFormatByAddMinute(Long minute) {
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();

        // 增加15分钟
        LocalDateTime plus15Minutes = now.plusMinutes(minute);

        // 创建一个DateTimeFormatter对象来定义日期时间的格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 将增加15分钟后的时间转换为字符串
        String formattedDateTime = plus15Minutes.format(formatter);

        // 输出结果
        System.out.println("当前时间: " + now.format(formatter));
        System.out.println("增加15分钟后的时间（字符串）: " + formattedDateTime);
        return formattedDateTime;
    }

    public static String currentDateFormat() {
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 创建一个DateTimeFormatter对象来定义日期时间的格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        final String format = now.format(formatter);
        // 输出结果
        System.out.println("当前时间: " + now.format(formatter));
        return format;
    }

    public static String currentDateYearFormat() {
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 创建一个DateTimeFormatter对象来定义日期时间的格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        final String format = now.format(formatter);
        // 输出结果
        System.out.println("当前时间: " + now.format(formatter));
        return format;
    }

    /**
     * 传入时间据当前时间相差几个月
     */
    public static Integer dateTimeFormat(String date) {
        Integer month = 0;
        LocalDateTime specifiedDateTime = LocalDateTime.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        // 当前时间
        LocalDateTime now = LocalDateTime.now();
        // 计算两个时间之间的月数
        Period period = Period.between(specifiedDateTime.toLocalDate(), now.toLocalDate());
        if (period.getMonths() == 0) {
            month = 1;
        } else {
            month = period.getMonths();
        }
        return month;
    }


    public static String longToString(long currentTime) {
        Date date = longToDate(currentTime);
        String strTime = dateToString(date, "yyyy-MM-dd");
        return strTime;
    }


    public static Date stringToDate(String strTime) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = formatter.parse(strTime);
        } catch (ParseException e) {

            e.printStackTrace();
        }
        return date;
    }

    public static String formatYear(String time, Integer year) {
        LocalDate now = LocalDate.parse(time, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        LocalDate plus = now.plusYears(year).plusDays(-1);
        return plus.toString();
    }

    public static void formatCurrentTime_StartTime() {
        // 假设有一个时间戳（以毫秒为单位）
        long timestamp = System.currentTimeMillis(); // 当前时间戳

        // 将时间戳转换为ZonedDateTime
        ZonedDateTime zonedDateTime = Instant.ofEpochMilli(timestamp)
                .atZone(ZoneId.systemDefault());
        // 获取当月的第一天
        LocalDate firstDayOfMonth = zonedDateTime.toLocalDate()
                .withDayOfMonth(1);
        // 将当月的第一天转换为ZonedDateTime，时间部分设置为00:00:00
        ZonedDateTime firstDayOfMonthZoned = firstDayOfMonth.atStartOfDay(ZoneId.systemDefault());
        // 计算时间差
        long daysDifference = ChronoUnit.DAYS.between(firstDayOfMonthZoned, zonedDateTime);
        long hoursDifference = ChronoUnit.HOURS.between(firstDayOfMonthZoned, zonedDateTime);
        long minutesDifference = ChronoUnit.MINUTES.between(firstDayOfMonthZoned, zonedDateTime);
        long secondsDifference = ChronoUnit.SECONDS.between(firstDayOfMonthZoned, zonedDateTime);
        // 输出结果
        System.out.println("距离当月第一天已经过去了：");
        System.out.println(daysDifference + " 天");
        System.out.println(hoursDifference + " 小时");
        System.out.println(minutesDifference + " 分钟");
        System.out.println(secondsDifference + " 秒");
    }


    public static Date longToDate(long currentTime) {
        Date dateOld = new Date(currentTime);
        String sDateTime = dateToString(dateOld, "yyyy-MM-dd HH:mm:ss");
        Date date = stringToDate(sDateTime);
        return date;
    }

    public static String dateToString(Date data, String formatType) {
        return new SimpleDateFormat(formatType).format(data);
    }

    public static String stringDateToMouth(String dateStr) {

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = formatter.parse(dateStr);
            String sDateTime = dateToString(date, "yyyy-MM");
            return sDateTime;
        } catch (ParseException e) {

            e.printStackTrace();
        }


        return null;
    }


    public static String czString(Long time) {
        Date date = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = sdf.format(date);

        System.out.println(formattedDateTime);
        return formattedDateTime;
    }

    public static List<String> getStrDateListBetween(String startDateString, String endDateString) {
        List<String> dateList = new ArrayList<>();

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            // 解析开始日期和结束日期
            Date startDate = dateFormat.parse(startDateString);
            Date endDate = dateFormat.parse(endDateString);

            // 创建 Calendar 实例并设置为开始日期
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(startDate);

            // 循环直到当前日期超过结束日期
            while (!calendar.getTime().after(endDate)) {
                // 将日期格式化为字符串，并添加到列表中
                dateList.add(dateFormat.format(calendar.getTime()));

                // 将日期加一天
                calendar.add(Calendar.DAY_OF_MONTH, 1);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return dateList;
    }

    public static Long strZLong(String time) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date date = dateFormat.parse(time);
            long timestamp = date.getTime();
            return timestamp;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0L;
    }


    public static Long strYearMonth(String time) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date date = dateFormat.parse(time);
            long timestamp = date.getTime();
            return timestamp;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0L;
    }

    public static String currentYearAndMonth() {

        // 获取当前日期
        LocalDate now = LocalDate.now();

        // 获取当前年份
        int year = now.getYear();

        // 获取当前月份并格式化为两位数字
        int month = now.getMonthValue();

        // 使用DateTimeFormatter格式化为字符串
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
        String currentYearMonth = String.format("%d-%02d", year, month);

        System.out.println(currentYearMonth); // 输出格式如: "2023-04"
        return currentYearMonth;

    }

    public static String currentAddMonthYearAndMonth() {

        // 获取当前日期
        LocalDate now = LocalDate.now();
        now = now.plusMonths(-1);
        // 获取当前年份
        int year = now.getYear();

        // 获取当前月份并格式化为两位数字
        int month = now.getMonthValue();

        // 使用DateTimeFormatter格式化为字符串
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
        String currentYearMonth = String.format("%d-%02d", year, month);

        System.out.println(currentYearMonth); // 输出格式如: "2023-04"
        return currentYearMonth;

    }


    public static String formatDateByYear(String date) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
        try {
            Date dateTime = dateFormat.parse(date); // 将字符串转换为 Date 对象
            String formattedDate = dateFormat.format(dateTime); // 正确使用
            return formattedDate;
        } catch (Exception e) {
            throw new ResultException("格式有误");
        }

    }

    public static String monthFirstDay(String dateString) {


        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        // 将字符串解析为LocalDate对象
        LocalDate date = LocalDate.parse(dateString, formatter);

        // 获取月份的第一天
        LocalDate firstDayOfMonth = date.withDayOfMonth(1);


        // 输出结果
        System.out.println("传入的时间: " + date);
        System.out.println("月份的第一天: " + firstDayOfMonth);
        return firstDayOfMonth.format(formatter);
    }

    public static String monthEndDay(String dateString) {
        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        // 将字符串解析为LocalDate对象
        LocalDate date = LocalDate.parse(dateString, formatter);
        // 获取月份的最后一天
        LocalDate lastDayOfMonth = YearMonth.from(date).atEndOfMonth();
        // 输出结果
        System.out.println("传入的时间: " + date);
        System.out.println("月份的最后一天: " + lastDayOfMonth);
        return lastDayOfMonth.format(formatter);
    }


    public static BigDecimal startTimeCompareEndTimeByRestHours(List<Map<String, String>> dateList) {
        Long hours = 0L;
        for (Map<String, String> stringStringMap : dateList) {
            String startTime = stringStringMap.get("startTime");
            String endTime = stringStringMap.get("endTime");
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            if (ObjectUtils.isEmpty(startTime) || ObjectUtils.isEmpty(endTime)) {
                continue;
            }
            LocalDateTime start = LocalDateTime.parse(startTime, formatter);
            LocalDateTime end = LocalDateTime.parse(endTime, formatter);
            Duration duration = Duration.between(start, end);
            System.err.println("休息时间" + duration.toMinutes());
            hours += duration.toMinutes() / 30;
        }

        System.err.println(hours);
        return new BigDecimal(hours).divide(new BigDecimal(2), 2, BigDecimal.ROUND_HALF_UP);
    }

    public static BigDecimal startTimeCompareEndTimeByWorkHours(List<Map<String, String>> dateList) {
        Long hours = 0L;
        for (Map<String, String> stringStringMap : dateList) {
            String startTime = stringStringMap.get("startTime");
            String endTime = stringStringMap.get("endTime");
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            if (ObjectUtils.isEmpty(startTime) || ObjectUtils.isEmpty(endTime)) {
                continue;
            }
            LocalDateTime start = LocalDateTime.parse(startTime, formatter);
            LocalDateTime end = LocalDateTime.parse(endTime, formatter);
            Duration duration = Duration.between(start, end);
            System.err.println("工作分钟数" + duration.toMinutes());
            boolean hasDecimal = (duration.toMinutes() % 60) != 0;
            if (hasDecimal) {
                hours += duration.toMinutes() / 60 + 1;
            } else {
                hours += duration.toMinutes() / 60;
            }
        }


        System.err.println(hours + "");
        return new BigDecimal(hours);
    }

    public static void main(String[] args) {
        Long minute = 0L;
        List<Map<String, String>> dateList = new ArrayList<>();
        Map<String, String> map1 = new HashMap<>();
        map1.put("startTime", "1970-01-01 12:00:00");
        map1.put("endTime", "1970-01-01 13:10:00");
        dateList.add(map1);
        for (Map<String, String> stringStringMap : dateList) {
            String startTime = stringStringMap.get("startTime");
            String endTime = stringStringMap.get("endTime");
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            if (ObjectUtils.isEmpty(startTime) || ObjectUtils.isEmpty(endTime)) {
                continue;
            }
            LocalDateTime start = LocalDateTime.parse(startTime, formatter);
            LocalDateTime end = LocalDateTime.parse(endTime, formatter);
            Duration duration = Duration.between(start, end);

            minute += duration.toMinutes();
//            System.err.println(hours);
        }
        boolean hasDecimal = (minute % 30) != 0;
        Long hours = minute / 60;
//        if (hasDecimal) {
//            hours = hours + 1;
//        }
        System.err.println(hours);
    }
}
